<template>
  <div v-loading="loading">
    <h3 class="title">云服务器实时可视化性能指标</h3>


    <div class="block">
      <el-button type="primary" style="margin-left: 10px;float:right;" class="el-icon-download" size="small" @click="serverInfoExport" v-if="area1">导出</el-button>
<!--      <el-select v-model="value4" clearable placeholder="请选择服务器">-->
<!--        <el-option-->
<!--            v-for="item in serverOptions"-->
<!--            :key="item.value"-->
<!--            :label="item.label"-->
<!--            :value="item.value">-->
<!--        </el-option>-->
<!--      </el-select>-->
<!--      <el-select v-model="value5" clearable placeholder="请选择云手机容器" style="margin-left: 10px">-->
<!--        <el-option-->
<!--            v-for="item in serverOptions"-->
<!--            :key="item.value"-->
<!--            :label="item.label"-->
<!--            :value="item.value">-->
<!--        </el-option>-->
<!--      </el-select>-->
<!--      <el-button type="primary" class="el-icon-search" size="small" style="margin-left: 10px">查询</el-button>-->
<!--      <el-date-picker-->
<!--          v-model="value2"-->
<!--          type="datetimerange"-->
<!--          :picker-options="pickerOptions"-->
<!--          range-separator="至"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--          align="right">-->
<!--      </el-date-picker>-->
<!--      <el-button type="primary" style="margin-left: 10px">确定</el-button>-->
    </div>
<!--    <el-divider></el-divider>-->
    <div class="outer">
    <div id="disk_container" style="height: 200px;width: 45%;float: left;">
      <p style="text-align: center">磁盘使用量(MB)</p>
    </div>
      <div id="memory_container" style="height: 200px;width: 45%;float: left;margin-left: 10px;">
        <p style="text-align: center">内存使用量(MB)</p>
      </div>
      <div style="width: 100%;height:50px;float:left;">
        <el-divider></el-divider>
      </div>
      <div id="totalCpu_container" style="height: 200px;width: 45%;float: left;">
        <p style="text-align: center">CPU整体占用率(%)</p>
      </div>
      <div id="gpu_container" style="height: 200px;width: 45%;float: left;margin-left: 10px;">
        <p style="text-align: center">GPU占用率(%)</p>
      </div>
      <div style="width: 100%;height:50px;float:left;margin-top: 10px;margin-left: 10px">
        <el-divider></el-divider>
      </div>
      <div id="column_container" style="height: 200px;width: 50%;margin: 0 auto">
        <p style="text-align: center">CPU多核心占用率(%)</p>
      </div>
    </div>
    <el-dialog
        title="导出信息填写"
        :visible.sync="exportVisible"
        width="30%"
        :show-close="false"
        :close-on-click-modal="false">

      <el-form ref="form" :model="exportForm" label-width="80px" inline :rules="exportRules">
        <el-form-item label="文件名" prop="name">
          <el-input v-model="exportForm.name"></el-input>
        </el-form-item>
        <el-form-item label="高度" prop="height">
          <el-input v-model="exportForm.height"></el-input>
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input v-model="exportForm.width"></el-input>
        </el-form-item>
      </el-form>
<!--      <span style="color: red">*高度建议300，宽度建议1200</span>-->
      <span style="color: red">{{wh}}</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="exportVisible = false">取 消</el-button>
    <el-button type="primary" @click="exportWord(exportForm.height,exportForm.width,'realGraph',exportForm.name),exportVisible = false">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import ip from "@/components/ip";
import { Area , Column} from '@antv/g2plot';
import {toDataURL} from "@/components/exportFunction";
import JSZipUtils from "jszip-utils";
import PizZip from "pizzip";
import docxtemplater from "docxtemplater";
import {exportMixin} from "../components/mixin";
import {realPerCpu, realPerf} from "@/api/server";
import {getWH} from "../components/getWH";
export default {
  name: "uploadPageCloud",

  data() {
    return {
      wh : '',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      value2: '',
      graphData: [],
      inter:null,
      interDisk:null,
      interMem:null,
      interGpu:null,
      interCpu:null,
      interColumn:null,
      area1:null,
      area2:null,
      area3:null,
      area4:null,
      area5:null,
      exportArea : {
        area1:null,
        area2:null,
        area3:null,
        area4:null,
        area5:null,
      },
      paletteSemanticRed : '#F4664A',
      brandColor : '#5B8FF9',
      value4:'ubuntu20',
      loading:false,
      serverOptions:[{
        value:'1',
        label:'ubuntu20'
      }],
      currentDiskValue:'',
      currentMemValue:''
    }
  },
  mixins : [exportMixin],
  mounted() {
    this.getDiskData()
    // this.getMemoryData()
    // this.getTotalCpuData()
    // this.getGpuData()
  },
  beforeDestroy() {
    clearInterval(this.interDisk)
    clearInterval(this.inter)
    clearInterval(this.interMem)
    clearInterval(this.interCpu)
    clearInterval(this.interGpu)
    clearInterval(this.interColumn)
    this.inter = null
    this.interDisk = null
    this.interMem = null
    this.interCpu = null
    this.interGpu = null
    this.interColumn = null
  },
  methods: {
    getDiskData() {
      let diskDataArray = []
      let memoryDataArray = []
      let gpuDataArray = []
      let totalCpuDataArray = []
      let totalPerCpuDataArray = []
      let cntD = 1;
      let cntM = 1;
      let cntC = 1;
      let cntG = 1;
      this.inter = setInterval(() => {
        realPerf(this.$store.state.server.serverId).then(res=>{
        // axios.get(this.$ip2 + '/server/perf/get?server_id=' + this.$store.state.server.serverId).then(res =>{
          this.currentDiskValue = res.data.server_rom_used
          this.currentMemValue = res.data.server_ram_used
          diskDataArray.push({
            timePeriod: this.getCurrentTime(),
            value: res.data.server_rom_used
          })
          memoryDataArray.push({
            timePeriod: this.getCurrentTime(),
            value: res.data.server_ram_used
          })
          totalCpuDataArray.push({
            timePeriod: this.getCurrentTime(),
            value: res.data.server_cpu_used
          })
          gpuDataArray.push({
            timePeriod: this.getCurrentTime(),
            value: res.data.server_gpu_used
          })
          realPerCpu(this.$store.state.server.serverId).then(res2=>{
          // axios.get(this.$ip2 + '/server/perf/cpuget?server_id=' + this.$store.state.server.serverId).then(res2=>{
            // 这里应该用循环来取出获取的数据
            if (totalPerCpuDataArray.length ===0) {
              for (let j =0;j < Object.keys(res2.data.serverCPU_used).length;j++) {
                totalPerCpuDataArray.push({
                  timePeriod:Object.keys(res2.data.serverCPU_used)[j],
                  value:Object.values(res2.data.serverCPU_used)[j]
                })
              }
            }
            else {
              for (let j =0;j < Object.keys(res2.data.serverCPU_used).length;j++) {
                totalPerCpuDataArray[j].value =  Object.values(res2.data.serverCPU_used)[j]
                totalPerCpuDataArray[j].timePeriod = Object.keys(res2.data.serverCPU_used)[j]
                // console.log(Object.values(res.data.server_cpu_percent)[j]);
              }
              console.log(totalPerCpuDataArray)
            }
          })


        })
      }, 3000);
      this.area1 = new Area('disk_container', {
        data: diskDataArray.slice(0, cntD),
        xField: 'timePeriod',
        yField: 'value',
        xAxis: {
          range: [0, 1],
        },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 1125144,
        //   min:0,
        //   // tickCount:6,
        //   // tickMethod:'quantile'
        // }
      });
      this.area2 = new Area('memory_container', {
        data: memoryDataArray.slice(0, cntM),
        xField: 'timePeriod',
        yField: 'value',
        xAxis: {
          range: [0, 1],
        },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 257157,
        //   min:0,
        //   tickCount:6,
        // }
      });
      this.area3 = new Area('totalCpu_container', {
        data: totalCpuDataArray.slice(0, cntC),
        xField: 'timePeriod',
        yField: 'value',
        xAxis: {
          range: [0, 1],
        },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   tickCount:6,
        // }
      });
      this.area4 = new Area('gpu_container', {
        data: gpuDataArray.slice(0, cntG),
        xField: 'timePeriod',
        yField: 'value',
        xAxis: {
          range: [0, 1],
        },
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   tickCount:6,
        // }
      });
      this.area5 = new Column('column_container', {
        data: totalPerCpuDataArray,
        xField: 'timePeriod',
        yField: 'value',
        // yAxis:{
        //   //这是实现y轴固定的关键
        //   type:'linear',
        //   max: 100,
        //   min:0,
        //   tickCount:6,
        // },
        seriesField: 'value',
        color: ({ value }) => {
          if (value < 0.05) {
            return this.paletteSemanticRed;
          }
          return this.brandColor;
        },
        // legend: false,
      });
      this.area1.render();
      this.area2.render();
      this.area3.render();
      this.area4.render();
      this.area5.render();
      this.interDisk = setInterval(() => {
      if (cntD === diskDataArray.length) {
        // clearInterval(interval);
      } else {
        cntD += 1;
        this.area1.changeData(diskDataArray.slice(0, -1));
      }
      }, 3000);
      this.interMem = setInterval(() => {
        if (cntM === memoryDataArray.length) {
          // clearInterval(interval);
        } else {
          cntM += 1;
          this.area2.changeData(memoryDataArray.slice(0, -1));
        }
      }, 3000);
      this.interCpu = setInterval(() => {
        if (cntC === totalCpuDataArray.length) {
          // clearInterval(interval);
        } else {
          cntC += 1;
          this.area3.changeData(totalCpuDataArray.slice(0, -1));
        }
      }, 3000);
      this.interGpu = setInterval(() => {
        if (cntG === gpuDataArray.length) {
          // clearInterval(interval);
        } else {
          cntG += 1;
          this.area4.changeData(gpuDataArray.slice(0, -1));
        }
      }, 3000);
      this.interColumn = setInterval(() => {
        this.area5.changeData(totalPerCpuDataArray.map((d) => ({ ...d, value: d.value })));
      }, 3000);
    },
    getMemoryData() {
      let dataArray = []
      let cnt = 1;
      const interval_memory = setInterval(() => {
        axios.get(ip + '/perf/add').then(res =>{
          dataArray.push({
            timePeriod: this.getCurrentTime(),
            value: res.data.memory_used
          })
          console.log(dataArray)
        })
      }, 1000);
      const area = new Area('memory_container', {
        data: dataArray.slice(0, cnt),
        xField: 'timePeriod',
        yField: 'value',
        xAxis: {
          range: [0, 1],
        },
      });
      area.render();
      const interval_memory2 = setInterval(() => {
        if (cnt === dataArray.length) {
          // clearInterval(interval);
        } else {
          cnt += 1;
          area.changeData(dataArray.slice(0, -1));
        }
      }, 2000);
    },
    getTotalCpuData() {
      let dataArray = []
      let cnt = 1;
      const interval_totalCpu = setInterval(() => {
        axios.get(ip + '/perf/add').then(res =>{
          dataArray.push({
            timePeriod: this.getCurrentTime(),
            value: res.data.CPU_total_percent
          })
          console.log(dataArray)
        })
      }, 1000);
      const area = new Area('totalCpu_container', {
        data: dataArray.slice(0, cnt),
        xField: 'timePeriod',
        yField: 'value',
        xAxis: {
          range: [0, 1],
        },
      });
      area.render();
      const interval_totalCpu2 = setInterval(() => {
        if (cnt === dataArray.length) {
          // clearInterval(interval);
        } else {
          cnt += 1;
          area.changeData(dataArray.slice(0, -1));
        }
      }, 2000);
    },
    getGpuData() {
      let dataArray = []
      let cnt = 1;
      const interval_gpu = setInterval(() => {
        axios.get(ip + '/perf/add').then(res =>{
          dataArray.push({
            timePeriod: this.getCurrentTime(),
            value: res.data.GPU_percent
          })
          console.log(dataArray)
        })
      }, 1000);
      const area = new Area('gpu_container', {
        data: dataArray.slice(0, cnt),
        xField: 'timePeriod',
        yField: 'value',
        xAxis: {
          range: [0, 1],
        },
      });
      area.render();
      const interval_gpu2 = setInterval(() => {
        if (cnt === dataArray.length) {
          // clearInterval(interval);
        } else {
          cnt += 1;
          area.changeData(dataArray.slice(0, -1));
        }
      }, 2000);
    },
    getCurrentTime() {
      //获取当前时间并打印
      let _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
      // _this.gettime = yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
      // console.log(this.gettime)
      return yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    },
    serverInfoExport() {
      this.wh = getWH('disk_container')
      this.exportVisible = true
    },
    getImg() {
      // console.log('src', toDataURL(this.line.chart))
      // var img = new Image();
      // img.src = this.chartInstance.getDataURL({
      //   pixelRatio: 2,
      //   backgroundColor: '#fff',
      //   type: 'png'
      // })
      this.exportArea.area1 = toDataURL(this.area1.chart)
      this.exportArea.area2 = toDataURL(this.area2.chart)
      this.exportArea.area3 = toDataURL(this.area3.chart)
      this.exportArea.area4 = toDataURL(this.area4.chart)
      this.exportArea.area5= toDataURL(this.area5.chart)
      // this.tableData.imgUrl = img.src
      // console.log('src', toDataURL(this.line.chart))
    },
    // Echarts图片处理
    base64DataURLToArrayBuffer(dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, "");
      let binaryString;
      if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
      } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    },
    //导出为word
    exportWord(height,width,module,name) {

      this.getImg();
      //这里要引入处理图片的插件，下载docxtemplater后，引入的就在其中了
      const ImageModule = require('docxtemplater-image-module-free');
      const _this = this;
      //Word路径，在public文件下(CLI3)
      JSZipUtils.getBinaryContent(`${module}.docx`, function (error, content) {
        if (error) {
          throw error
        }
        let opts = {}
        opts.centered = true;
        opts.fileType = "docx";
        opts.getImage = (tag) => {
          return _this.base64DataURLToArrayBuffer(tag);
        }
        opts.getSize = () => {
          return [width, height]//这里可更改输出的图片宽和高
        }

        let zip = new PizZip(content);
        let doc = new docxtemplater();
        doc.attachModule(new ImageModule(opts));
        doc.loadZip(zip);
        // 这里是设置导出的数据
        doc.setData({
          exportArea : _this.exportArea
          // arr: _this.arr // 评语
        })
        try {
          doc.render()
        } catch (error) {
          var e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          }
          console.log(JSON.stringify({
            error: e
          }));
          throw error;
        }
        const out = doc.getZip().generate({
          type: "blob",
          mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        })
        saveAs(out, `${name}.docx`)
      })
    },
  }
}
</script>

<style scoped>
.card {
  position: relative;
  width: 900px;
  max-width: 100%;
  padding: 60px 35px 0;
  margin: 15px auto;
  overflow: hidden;
}

.block{
  margin-left: 10px;
}
</style>
